<template>
    <div v-if="showInput" class="mulite-entry-warrper">
        <div class="mulite-entry">
            <base-select
                :selectProps="{ clearable: false }"
                :value.sync="currentType"
                class="base-select"
                :item="{ options: muliteEntryOptions }"
                @selectChange="selectChange"
            />
            <!-- 条形码输入框 -->
            <base-input
                :inputProps="{
                    placeholder: currentPlaceholder
                }"
                class="base-input"
                :value.sync="barcode"
                @keydown.native.enter="submitInput"
            />
            <!-- sku的级联选择 只有 sku 选择的时候才有 -->
            <baseCascader
                v-if="currentType === 0 || currentType === 4"
                :options="skuCadcader"
                :selectProps="{
                    size: 'small'
                }"
                :value.sync="skuChoose"
                class="cascader-box"
            />
            <!-- 数量输入框 -->
            <base-number-input v-if="[100, 0, 1, 4].includes(currentType)" :value.sync="barcodeNumber" @keydown.native.enter="submitInput" />
            <el-tooltip v-if="[100, 0, 1, 4].includes(currentType)" placement="top" class="mglr-10">
                <div slot="content">
                    {{ $t('commonWord.evenCodeNumRules') }}<br />{{ $t('commonWord.evenCodeNumMiuns') }}；<br />
                    {{ $t('commonWord.evenCodeNumAdd') }}
                </div>
                <i class="el-icon-warning-outline" />
            </el-tooltip>
            <el-button type="primary" @click="submitInput('click')">
                {{ $t('commonWord.input') }}
            </el-button>
            <!-- 齐码 只有 sku 和 条码的时候才用到 -->
            <el-tooltip v-if="[0, 1, 4].includes(currentType) && evenCodeEnabled" placement="top" class="tooltip-icon">
                <div slot="content">
                    1.{{ $t('commonWord.evenCodeTips') }}；<br />
                    2.{{ $t('commonWord.evenCodeToolRules') }}
                </div>
                <el-checkbox v-model="evenCode" class="invalid f14 mgl-10">
                    {{ $t('commonWord.evenCode') }}<i class="el-icon-warning-outline mgl-6" />
                </el-checkbox>
            </el-tooltip>

            <slot name="enterPrice">
                <el-checkbox v-model="enterPrice" class="invalid f14 mgl-10" @change="exterPriceChange">
                    {{ $t('commonWord.enterPrice') }}
                </el-checkbox>
            </slot>

            <slot name="other" />
        </div>
        <!-- <slot name="barcodeRecord">
      <barcode-record
        ref="barcodeRecord"
        :barcodeRecord="v_barcodeRecord" />
    </slot> -->
        <!-- 货品模糊搜索的弹窗 -->
        <base-dialog :dialogObj="dialogObj" class="base-dialog">
            <template v-slot:content>
                <base-input
                    :inputProps="{
                        placeholder: 'form.placeholder.goodsFielsPlaceholder',
                        suffixIcon: 'el-icon-search'
                    }"
                    :value.sync="barcode"
                    class="long-input"
                    @enter="goodsBarcode"
                />
                <base-table
                    :tableData="tableData"
                    :colunmData="tableHeader"
                    :tableConfig="{
                        isMultiSelect: false,
                        isIndex: true,
                        isShowOpera: false
                    }"
                    @viewDetail="viewDetail"
                />
            </template>
            <template v-slot:footerBtn>
                <!-- <div class="empty" /> -->
                <small-pagination :total="page.total" class="mgb-8" @changePage="changePage" @changePageSize="changePageSize" />
            </template>
        </base-dialog>
    </div>
</template>

<script lang="ts">
import Vue from 'vue';
import Component from 'vue-class-component';
import { Prop } from 'vue-property-decorator';
import { Options, Dictionary, DialogObj, CascaderOptionsConfig, TableHeaderConfig, PageObj } from '@/typings';
import scanRequest from '@/api/common-api/scan';
// import { Tools } from '@/utils/tools'
// import apiUrl from '@/api/packingwork/packingworktop'
// import commonApi from '@/api/common-api'
// 0 货品 1条形码 2唯一码 3箱号 4助记码(和货号录入逻辑一样) 100 是自动识别
type SCAN_TYPE = 0 | 1 | 2 | 3 | 4 | 100;
const PLACEHOLDERMAP = {
    100: 'form.placeholder.mulitPlaceholder',
    0: 'form.placeholder.goodsInput',
    1: 'form.placeholder.barcodeInput',
    2: 'form.placeholder.onlyCodePlaceholder',
    3: 'form.placeholder.boxInput',
    4: 'form.placeholder.MnemonicCodeEntry'
};
@Component({
    name: 'mulite-entry',
    components: {
        baseSelect: () => import('@/components/base-select/index.vue'),
        baseInput: () => import('@/components/base-input/index.vue'),
        baseNumberInput: () => import('@/components/base-inputNumber/index.vue'),
        baseCascader: () => import('@/components/base-cascader/index.vue'),
        baseDialog: () => import('@/components/base-dialog/index.vue'),
        baseTable: () => import('@/components/base-table/index.vue'),
        smallPagination: () => import('@/components/small-pagination/index.vue'),
        barcodeRecord: () => import('@/layout-components/barcode-record/index.vue')
    }
})
export default class muliteEntry extends Vue {
    // @Prop({ required: true }) formdata: Dictionary
    // 显示扫描类型
    @Prop({
        default: () => {
            return [0, 1, 2, 3, 4, 100];
        }
    })
    scanType: SCAN_TYPE[];
    // 扫码前必须校验的字段
    // @Prop({ default: () => { return [] } }) authRequest: any[]
    @Prop({ default: true }) evenCodeEnabled;
    // 这里直接取formData数据
    @Prop({ required: true }) requestExData: Dictionary;
    // 删除指定约束
    @Prop({
        default: () => {
            return [];
        }
    })
    cancelCheckParameter: string[];
    // 扫描类型
    @Prop({ required: false, default: 'public' }) sweepType: any;
    // 用于识别单据字段转换ids[]
    @Prop() billFiled: string;
    barcode: string = '';
    barcodeNumber: number = 1;
    evenCode: boolean = false;
    currentType: SCAN_TYPE = 100;
    currentPlaceholder: string = PLACEHOLDERMAP[100];
    skuCadcader: CascaderOptionsConfig[] = [];
    skuChoose: string | number[] = [];
    page: PageObj = {
        total: 0,
        pageCount: 1,
        pageSize: 10,
        pageNo: 1
    };
    barcodeRecord: any[] = [];
    dialogObj: DialogObj = {
        isShowDialog: false,
        title: ''
    };
    tableHeader: TableHeaderConfig[] = [
        {
            label: '货品货号',
            value: 'goodsCode',
            en: 'Item Number',
            lang: 'barcode.list.tableHeader.code'
        },
        {
            label: '货品名称',
            value: 'goodsName',
            en: 'Product Name',
            lang: 'barcode.list.tableHeader.name'
        }
    ];
    tableData: any[] = [];
    enterPrice: boolean = false;
    goodsCode: string = '';
    goodsId: string = '';
    v_vuexStore: Dictionary = {};

    // get v_barcodeRecord() {
    //   return this.$store.state[this.$route.meta.moduleId].v_barcodeRecord || []
    // }

    get v_barcodeRecord() {
        return this.v_vuexStore.v_barcodeRecord;
    }
    // 显示该组件的条件
    get showInput() {
        return !['detail', 'cancel', ''].includes(this.v_vuexStore.v_status);
    }

    get hasLong() {
        return localStorage.getItem('Use_Long') === 'true';
    }
    get muliteEntryOptions() {
        const options: Options[] = [
            {
                label: '自动识别',
                value: 100,
                lang: 'commonWord.automatic'
            },
            {
                label: '货品SKU录入',
                value: 0,
                lang: 'commonWord.goodsEntry'
            },
            {
                label: '条码录入',
                value: 1,
                lang: 'commonWord.barcodeEntry'
            },
            {
                label: '唯一码录入',
                value: 2,
                lang: 'commonWord.onlyKeyEntry'
            },
            {
                label: '箱号录入',
                value: 3,
                lang: 'commonWord.boxEntry'
            },
            {
                label: '助记码录入',
                value: 4,
                lang: 'commonWord.MnemonicCodeEntry'
            }
        ];
        // return options.filter((item) => this.scanType.includes(item.value as SCAN_TYPE))
        // 助记码默认有
        return options.filter((item) => [...this.scanType, 4].includes(item.value as SCAN_TYPE));
    }
    created() {
        this.$nextTick(() => {
            // 这里是根据vuex 在用一个对象进行接受  因为用 计算属性 moduleId 变了 计算属性也会跟着变 导致后面 watch v_status 也会再次执行
            const moduleId = JSON.parse(JSON.stringify(this.$route.meta.moduleId));
            this.v_vuexStore = this.$store.state[moduleId];
        });
    }
    viewDetail(row) {
        this.dialogObj.isShowDialog = false;
        this.barcode = row.goodsCode;
        this.goodsId = row.goodsId;
        this.skuCadcader = row.colorList;
    }
    // sku列表换页容
    changePageSize(size) {
        this.page['pageSize'] = size;
        // this.goodsFuzzySearch()
        this.goodsBarcode();
    }
    // sku列表换页码
    changePage(page) {
        this.page['pageNo'] = page;
        // this.goodsFuzzySearch()
        this.goodsBarcode();
    }
    // 校验前置必填字段
    // validateFields() {
    //   for (let a = 0; a < this.authRequest.length; a++) {
    //     const em = this.authRequest[a]
    //     if (Tools.isEmpty(this.formdata[em.value])) {
    //       this.$message.warning(em.msg)
    //       return
    //     }
    //   }
    // }
    // 是否录入新价格的数据变化
    exterPriceChange() {
        this.$emit('exterPriceChange', this.enterPrice);
    }
    submitInput(type?) {
        // console.log('type', type, 'this.currentType', this.currentType);
        // 如果类别为 1 则是自动识别 需要先识别是那个条码类型
        switch (this.currentType) {
            case 100:
                this.automaticBarcode(type);
                break;
            // 货品录入
            case 0:
            case 4:
                if (type === 'click') {
                    this.emitSkuChoose();
                } else {
                    // 获取 货品的数据
                    this.goodsBarcode();
                }
                break;
            // 条形码录入
            case 1:
                this.skuBarcode();
                break;
            case 2:
                // 唯一码录入
                this.onlyBarcode();
                break;
            case 3:
                // 箱录入
                this.boxInput();
                break;
            default:
                break;
        }
    }
    // 自动识别
    async automaticBarcode(type) {
        const res = await this._post({
            url: scanRequest.auto,
            data: {
                data: {
                    keyWord: this.barcode
                }
            }
        });
        if (res.code === 0) {
            this.currentType = res.data;
            this.submitInput(type);
        }
    }

    // 删除指定约束条件
    deleteCheckParameter(array: string[]) {
        const copyPaste = JSON.parse(JSON.stringify(array));
        if (this.cancelCheckParameter.length) {
            this.cancelCheckParameter.forEach((em) => {
                copyPaste.splice(copyPaste.indexOf(em), 1);
            });
        }
        return copyPaste;
    }
    /**
     * 货品录入
     * 1. 根据填写的货品得到货品列表 如果之匹配到一个 就是精确搜索 如果多个 弹出弹窗选择
     * 2. 根据选择的货品 获取到 颜色尺码类别 组装成级联
     * 3. 根据选择的 sku 去更新数据
     */
    async goodsBarcode() {
        const requestData = scanRequest.requestCheck(
            this.deleteCheckParameter(scanRequest.parameterConstraint[this.sweepType].skuPage),
            {
                keyWord: this.barcode,
                moduleId: this.$route.meta.moduleId,
                ...this.requestExData,
                billIdList: this.billFiled
                    ? this.requestExData[this.billFiled]
                        ? Array.isArray(this.requestExData[this.billFiled])
                            ? this.requestExData[this.billFiled]
                            : [this.requestExData[this.billFiled]]
                        : undefined
                    : undefined
            },
            this.sweepType
        );
        // console.log('requestData', requestData);
        if (requestData) {
            this.skuChoose = [];
            const res = await this._post({
                url: scanRequest.requestInterface(this.sweepType, 'skuPage'),
                data: {
                    data: Object.assign({}, requestData, {
                        keyWordType: this.currentType === 0 ? 0 : 1
                    }),
                    page: this.page.pageNo,
                    pageSize: this.page.pageSize
                }
            });
            if (res.code === 0) {
                const { total, data, pageCount, pageSize } = res;
                this.tableData = data;
                this.page = Object.assign({}, this.page, {
                    total,
                    pageSize,
                    pageCount
                });
                //  只有一条数据则是精确搜索 给级联赋值
                if (this.page.total === 1) {
                    this.getSkuCascader(this.tableData[0]);
                    return;
                }
                this.openDialog();
            }
        }
    }

    getSkuCascader(config) {
        this.goodsId = config.goodsId;
        this.skuCadcader = config.colorList;
    }
    // 货品模糊搜索的弹窗
    openDialog() {
        this.dialogObj.isShowDialog = true;
        this.dialogObj.title = this.$t('form.placeholder.goodsInput');
    }
    // 选择 sku 后触发的事件
    emitSkuChoose() {
        if (this.skuChoose.length === 0) {
            this._message({ message: '请选择sku数据', type: 'warning' });
            return;
        }
        const scanType = this.getScanType();

        this.$emit(
            'skuChoose',
            {
                colorId: this.skuChoose[0],
                longId: this.hasLong ? this.skuChoose[1] : '',
                sizeId: this.hasLong ? this.skuChoose[2] : this.skuChoose[1],
                ...this.requestExData,
                quantity: this.barcodeNumber,
                keyword: this.barcode,
                fullSizeFlag: this.evenCode,
                enterPriceFlag: this.enterPrice,
                goodsId: this.goodsId,
                scanType
            },
            this.resetEcterPriceFlagFn
        );
    }
    // 条形码录入
    async skuBarcode() {
        const scanType = this.getScanType();
        this.$emit(
            'skuBarcode',
            {
                keyword: this.barcode,
                ...this.requestExData,
                quantity: this.barcodeNumber,
                fullSizeFlag: this.evenCode,
                enterPriceFlag: this.enterPrice,
                scanType
            },
            this.resetEcterPriceFlagFn
        );
    }
    resetEcterPriceFlagFn() {
        this.enterPrice = false;
    }
    // 唯一码录入
    async onlyBarcode() {
        const scanType = this.getScanType();

        this.$emit('onlyBarcode', {
            keyWord: this.barcode,
            quantity: this.barcodeNumber,
            fullSizeFlag: this.evenCode,
            enterPriceFlag: this.enterPrice,
            scanType,
            ...this.requestExData
        });
    }
    // 箱号录入
    boxInput() {
        const scanType = this.getScanType();

        this.$emit('boxInput', {
            keyWord: this.barcode,
            scanType,
            ...this.requestExData
        });
    }
    selectChange(value) {
        this.currentType = value;
        this.currentPlaceholder = PLACEHOLDERMAP[value];
        this.barcode = '';
        this.barcodeNumber = 1;
    }
    // 扫描记录
    getScanType() {
        let scanType: number = 0;
        const classify = (type) => {
            switch (true) {
                case type === 0:
                    return this.evenCode ? 4 : 0;
                case type === 1:
                    return this.evenCode ? 5 : 1;
                case type === 2:
                    return 2;
                case type === 3:
                    return 3;
                default:
                    return 0;
            }
        };
        scanType = classify(this.currentType);
        return scanType;
    }
}
</script>
<style lang="scss">
.base-dialog {
    .el-dialog__body {
        padding: 0 16px;
    }
    .el-dialog__footer {
        padding: 12px 16px 16px 16px;
    }
}
</style>
<style scoped lang="scss">
@import 'src/styles/variables.scss';
.mulite-entry {
    position: relative;
    display: inline-flex;
    height: 28px;
    align-items: center;
    width: 100%;
    .base-input {
        width: 200px;
        // margin-right: 10px;
        margin: 0 10px 0 8px;
    }
    .tooltip-icon {
        margin: 0 10px;
    }
    .base-select {
        width: 130px !important;
        height: 28px !important;
        /deep/.el-input__inner {
            height: 28px !important;
            line-height: 28px !important;
        }
    }
    .cascader-box {
        margin-right: 10px;
        width: 200px;
    }
    /deep/.el-checkbox__label {
        font-size: 14px;
        color: $colorTextSecondary;
    }
}
.long-input {
    width: 200px;
    margin: 8px 0;
}
</style>
